package com.txazo.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.txazo.dao.BaseDao;

/**
 * Hibernate通用Dao实现
 * 
 * @author txazo
 * @since 1.0
 */
@Repository("baseDao")
public class BaseDaoImpl implements BaseDao {

	@Autowired
	private HibernateTemplate hibernateTemplate;

	@Override
	public <T> void save(T t) {
		hibernateTemplate.save(t);
	}

	@Override
	public <T> void delete(T t) {
		hibernateTemplate.delete(t);
	}

	@Override
	public <T> void delete(Class<T> entityClass, Integer id) {
		hibernateTemplate.delete(get(entityClass, id));
	}

	@Override
	public <T> void update(T t) {
		hibernateTemplate.update(t);
	}

	@Override
	public <T> T get(Class<T> entityClass, Integer id) {
		return hibernateTemplate.get(entityClass, id);
	}

	@Override
	public <T> List<T> findAll(String hql, Class<T> entityClass) {
		return (List<T>) hibernateTemplate.find(hql);
	}

	@Override
	public <T> List<T> findAll(String hql, Class<T> entityClass, Object param) {
		return (List<T>) hibernateTemplate.find(hql, param);
	}

	@Override
	public <T> List<T> findAll(String hql, Class<T> entityClass, Object[] params) {
		return (List<T>) hibernateTemplate.find(hql, params);
	}

	@Override
	public <T> List<T> findByPage(final String hql, Class<T> entityClass,
			final int firstResult, final int maxResult) {
		return findByPage(hql, entityClass, new Object[] {}, firstResult,
				maxResult);
	}

	@Override
	public <T> List<T> findByPage(final String hql, Class<T> entityClass,
			final Object param, final int firstResult, final int maxResult) {
		return findByPage(hql, entityClass, new Object[] { param },
				firstResult, maxResult);
	}

	@Override
	public <T> List<T> findByPage(final String hql, Class<T> entityClass,
			final Object[] params, final int firstResult, final int maxResult) {
		List list = hibernateTemplate.executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(hql);
				for (int i = 0; i < params.length; i++) {
					query.setParameter(i, params[i]);
				}
				List result = query.setFirstResult(firstResult).setMaxResults(
						maxResult).list();
				return result;
			}
		});
		return (List<T>) list;
	}

}
